import fs from 'fs';
import etag from 'etag';
import http from 'http';

import setHeader from '../header';
import { IServer } from '../../common/serve';
import { getAssetPath, getSuffix } from '../common/util';

/**
 * 响应
 */
function end (request: http.IncomingMessage, response: http.ServerResponse, assetPath: string): void {
    const { headers } = request;

    const ifNoneMatch = headers['if-none-match'];
    const isCache = ifNoneMatch && ifNoneMatch === etag(fs.statSync(assetPath));

    if (isCache) {
        response.statusCode = 304;
        response.end();
    } else {
        setHeader(request, response, assetPath, getSuffix(assetPath), false);

        const readStream = fs.createReadStream(assetPath);

        readStream.on('data', chunks => {
            response.write(chunks);
        });

        readStream.on('end', () => {
            response.statusCode = 200;
            response.end();
        });
    }
}

function defaultMod (request: http.IncomingMessage, response: http.ServerResponse, serverConfig: IServer, assetPath: string): void {
    const { headers } = request;

    if (fs.existsSync(assetPath)) {
        end(request, response, assetPath);
        return;
    }

    const contentType = headers['content-type'];
    if (!contentType || /html$/.test(contentType)) {
        const rewriteAssetsPath = getAssetPath(serverConfig.assetsDirPath, serverConfig.rewrite);
        if (fs.existsSync(rewriteAssetsPath)) {
            end(request, response, rewriteAssetsPath);
        }
    } else {
        response.statusCode = 404;
        response.end();
    }
}

export default defaultMod;
